package com.cskaoyan.service.admin.auth.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.po.admin.MarketPrePermissionPo;
import com.cskaoyan.bean.vo.admin.auth.Md5Util;
import com.cskaoyan.bean.vo.wx.auth.WxUserUtil;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.mapper.admin.MarketPrePermissionMapper;
import com.cskaoyan.service.admin.auth.AuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author bwj
 * @date 2022/09/06 20:47
 *
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    MarketAdminMapper marketAdminMapper;
    @Autowired
    MarketPermissionMapper marketPermissionMapper;
    @Autowired
    MarketRoleMapper marketRoleMapper;
    @Autowired
    MarketPrePermissionMapper prePermissionMapper;

    //TODO bwj,后台管理员登录
    @Override
    public LoginUserData login(String username,String password) {
        Subject subject = SecurityUtils.getSubject();
        //执行登录
        String pwd=null;
        try {
            pwd = Md5Util.getMd5(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
        //登录不成功会发生异常
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return null;
        }
        //判断是否认证成功
        if (subject.isAuthenticated()) {
            //记录用户登录时间
            MarketAdmin admin = new MarketAdmin();
            admin.setLastLoginTime(new Date());
            MarketAdminExample adminExample = new MarketAdminExample();
            adminExample.createCriteria().andIdEqualTo(WxUserUtil.adminUtil().getId());
            marketAdminMapper.updateByExampleSelective(admin, adminExample);
        }
        //获取session信息
        Session session = subject.getSession();
        //获得principal信息
        //realm那边传入的第一个参数
        MarketAdmin principal = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();
        adminInfo.setAvatar(principal.getAvatar());
        adminInfo.setNickName(principal.getUsername());
        loginUserData.setAdminInfo(adminInfo);
        loginUserData.setToken((String) session.getId());
        return loginUserData;
    }

    //TODO bwj,后台管理员登出
    /**
    * @Author: 宾文杰 @Description:后台管理员登出  @Date: 2022/9/6
    */
    @Override
    public void logout() {

    }

    @Override
    public InfoData authInfo(String token) {
        //开发完shiro之后，再整合
        InfoData infoData = new InfoData();
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String id = (String) session.getId();
        //如果sessionId正确，则获得对应信息
        if (token.equals(id)) {
            PrincipalCollection principals = subject.getPrincipals();
            MarketAdmin principal = (MarketAdmin) principals.getPrimaryPrincipal();
            infoData.setName(principal.getUsername());
            infoData.setAvatar(principal.getAvatar());
            ArrayList<String> roles = new ArrayList<>();
            Integer[] roleIds = principal.getRoleIds();
            ArrayList<String> permissions =new ArrayList<>();
            //有多个角色时，获取权限总和
            if (roleIds.length!=0&&roleIds.length != 1) {
                for (int i = 0; i < roleIds.length; i++) {
                    int roleId = roleIds[i];
                    //TODO 根据角色id获得对应角色信息
                    MarketRole marketRole = marketRoleMapper.selectByPrimaryKey(roleId);
                    roles.add(marketRole.getName());
                    //TODO 根据角色id获得权限
                    List<MarketPrePermissionPo> marketPrePermissionPos = prePermissionMapper.selectPreOPermission(roleId);
                    for (MarketPrePermissionPo prePermissionPo : marketPrePermissionPos) {
                        String permission = prePermissionPo.getPermission();
                        permissions.add(permission);
                    }
                }
                infoData.setRoles(roles);
                infoData.setPerms(permissions);
            } else if(roleIds.length!=0){
                int roleId = roleIds[0];
                MarketRole marketRole = marketRoleMapper.selectByPrimaryKey(roleId);
                roles.add(marketRole.getName());
                List<MarketPrePermissionPo> marketPrePermissionPos = prePermissionMapper.selectPreOPermission(roleId);
                for (MarketPrePermissionPo prePermissionPo : marketPrePermissionPos) {
                    String permission = prePermissionPo.getPermission();
                    permissions.add(permission);
                }
                infoData.setRoles(roles);
                infoData.setPerms(permissions);
            }else {
                //没有角色
                infoData.setRoles(roles);
                infoData.setPerms(permissions);
            }
            return infoData;
        }
        return null;
    }
}
